//
//  JKVideoManager.m
//  Baisi
//
//  Created by albert on 2018/3/20.
//  Copyright © 2018年 安永博. All rights reserved.
//

#import "JKVideoManager.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "JKPostModel.h"
#import "JKDeleteJsonNull.h"

static NSString *VideoCacheDirectoryName_ = @"Videos"; // 视频拍摄存放目录
static NSString *VideoInfoName_ = @"videoInfo.plist";   // 视频记录的文件
static NSString *VideoUrlToFileNameInfo_ = @"videoUrlToFileNameInfo.plist";   // 视频URL和文件名对应的字典文件

static NSString *videoDirectoryPath_;  // 保存视频的文件夹路径
static NSString *videoInfoPath_;  // videoInfo.plist 路径

@implementation JKVideoManager

/** 视频缓存文件夹文件总大小 */
+ (NSString *)videoCacheSize{
    
    NSDictionary *fileInfo = [self videoCacheDirectoryInfo];
    
    return fileInfo[NSFileSize];
}

/** 视频缓存文件夹的信息 */
+ (NSDictionary *)videoCacheDirectoryInfo{
    
    NSDictionary *fileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:[self videoDirectoryPath] error:nil];
    
    return fileInfo;
}

/** 保存视频的文件夹名称 */
+ (NSString *)videoCacheDirectoryName{
    
    return VideoCacheDirectoryName_;
}

/** videoInfo.plist 文件夹名 即@"videoInfo.plist" */
+ (NSString *)videoInfoName{
    
    return VideoInfoName_;
}

/** 保存视频的文件夹路径 */
+ (NSString *)videoDirectoryPath{
    
    if (!videoDirectoryPath_) {
        
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        
        // 视频缓存文件夹路径
        videoDirectoryPath_ = [path stringByAppendingPathComponent:VideoCacheDirectoryName_];
    }
    
    return videoDirectoryPath_;
}

/** videoInfo.plist 路径 */
+ (NSString *)videoInfoPath{
    
    if (!videoInfoPath_) {
        
        // 保存视频信息的文件路径
        videoInfoPath_ = [[self videoDirectoryPath] stringByAppendingPathComponent:VideoInfoName_];
    }
    
    return videoInfoPath_;
}

/** 视频是否已缓存 */
+ (BOOL)videoExistWithUrl:(NSString *)url{
    
    return [[NSFileManager defaultManager] fileExistsAtPath:[self videoPathWithUrl:url]];
}

/** 删除缓存的视频 */
+ (BOOL)deleteVideWithUrl:(NSString *)url{
    
    if ([self videoExistWithUrl:url]) {
        
        
        BOOL isDeleted = [[NSFileManager defaultManager] removeItemAtPath:[self videoPathWithUrl:url] error:nil];
        
        if (!isDeleted) {
            
            return isDeleted;
        }
        
        NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:[self videoInfoPath]];
        
        NSDictionary *removeDict = nil;
        
        for (NSDictionary *dict in arr) {
            
            if ([dict[@"videouri"] isEqualToString:url]) {
                
                removeDict = dict;
                
                break;
            }
        }
        
        [arr removeObject:removeDict];
        
        if (![arr writeToFile:[self videoInfoPath] atomically:YES]) {
            
            JKLog(@"info文件写入失败!");
        }
        
        return isDeleted;
    }
    
    return YES;
}

/** 获取视频缓存的路径 */
+ (NSString *)videoPathWithUrl:(NSString *)url{
    
    NSString *fileName = [NSString stringWithFormat:@"%@%@", url.md5String, url.lastPathComponent];
    
    return [[self videoDirectoryPath] stringByAppendingPathComponent:fileName];
}

+ (void)downloadVideoWithPostModel:(JKPostModel *)model
                          progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                 completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self videoDirectoryPath]]) {
        
        if (![[NSFileManager defaultManager] createDirectoryAtPath:[self videoDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil]) {
            
            JKLog(@"创建文件夹失败!");
            
            return;
        }
    }
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self videoInfoPath]]) {
        
        NSArray *videos = @[];
        
        if (![videos writeToFile:[self videoInfoPath] atomically:YES]) {
            
            JKLog(@"创建info文件失败!");
        }
    }
    
    NSString *fileName = [NSString stringWithFormat:@"%@%@", model.videouri.md5String, model.videouri.lastPathComponent];
    
    NSString *videoPath = [[self videoDirectoryPath] stringByAppendingPathComponent:fileName];
    
    NSURL *videoURL = [NSURL fileURLWithPath:videoPath];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
        
        [self saveVideoToAlbum:videoURL isCached:YES];
        
        !completionHandler ? : completionHandler(nil, videoURL, nil);
        
        return;
    }
    
    NSURLSessionDownloadTask *downloadTask = [[AFHTTPSessionManager manager] downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.videouri]] progress:downloadProgressBlock destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        JKLog(@"%@", videoPath);
        
        return videoURL;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        !completionHandler ? : completionHandler(response, filePath, error);
        
        if (error) {
            
            [JKProgressHUD showErrorWithStatus:@"下载失败！"];
            
            return;
        }
        
        JKLog(@"%@", response);
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath.path]) {
            
            NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:[self videoInfoPath]];
            
            NSMutableDictionary *videoDict = [model mj_keyValuesWithKeys:@[@"ID", @"profile_image", @"name", @"text", @"create_time", @"ding", @"cai", @"comment", @"repost", @"weixin_url", @"sina_v", @"small_image", @"large_image", @"middle_image", @"width", @"height", @"type", @"playcount", @"videotime", @"videouri"]];
            videoDict[@"fileName"] = fileName;
            
            NSDictionary *fileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath.path error:nil];
            videoDict[@"fileSize"] = fileInfo[NSFileSize];
            
            [arr insertObject:videoDict atIndex:0];
            
            if (![arr writeToFile:[self videoInfoPath] atomically:YES]) {
                
                JKLog(@"info文件写入失败!");
            }
        }
        
        [self saveVideoToAlbum:filePath isCached:NO];
    }];
    
    [downloadTask resume];
}

/** 保存到相册
 * filePath: 缓存路径url
 * isCached: 是否已经缓存过
 */
+ (void)saveVideoToAlbum:(NSURL *)filePath isCached:(BOOL)isCached{
    
    [JKAlertView alertViewWithTitle:@"视频已经缓存，是否直接保存至相册？" message:nil style:(JKAlertStylePlain)].addAction([JKAlertAction actionWithTitle:@"不用了" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
        
        
    }]).addAction([JKAlertAction actionWithTitle:@"保存至相册" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
        
        [self saveVideoToAlbum:filePath];
        
    }]).show();
}

+ (void)saveVideoToAlbum:(NSURL *)filePath{
    
    [JKProgressHUD showWithStatus:@"正在保存至相册..." isAllowUserAction:NO];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [[[ALAssetsLibrary alloc] init] writeVideoAtPathToSavedPhotosAlbum:filePath completionBlock:^(NSURL *assetURL, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (error) {
                    
                    JKLog(@"%@", error);
                    
                    [JKProgressHUD showErrorWithStatus:@"保存失败！"];
                    
                }else{
                    
                    [JKProgressHUD showSuccessWithStatus:@"已保存至相册！"];
                }
            });
        }];
    });
}
@end
